package com.sangu.dianxiu.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.sangu.dianxiu.ICallBack;
import com.sangu.dianxiu.R;
import com.sangu.dianxiu.bean.repairer.AroundMasterEntity;
import com.sangu.dianxiu.utils.MasterManager;


import java.util.ArrayList;
import java.util.HashMap;

//显示周边师傅的Activity
public class ShowMasterActivity extends BaseActivity implements BDLocationListener {

    private MasterManager masterManager=new MasterManager();    //使用此类进行网络数据请求
    private BaiduMap mBaiduMap;
    private LocationClient locationClient;
    private View popView;       //点击覆盖物弹出的视图界面
    private ArrayList<AroundMasterEntity.RepairersEntity> aroundMasters=new ArrayList<>();  //周边师傅信息
    @ViewInject(R.id.bmap_activity_show_master)     //使用xutils的框架注解，这样就不用findViewById了
    private MapView mMapView;
    @ViewInject(R.id.iv_activity_show_master_back)
    private ImageView ivBack;                       //ActionBar上面的返回图标
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_master);
        ViewUtils.inject(this);                     //使用xutils框架进行注解，这样xutils注解才会生效
        initMap();                                  //初始化百度地图
        initLocation();                             //初始化定位
    }
    private void initMap() {
        mBaiduMap = mMapView.getMap();

        //不能移除百度地图logo
        //mMapView.removeViewAt(1);
    }
    @OnClick({R.id.iv_activity_show_master_back})       //使用xutils的点击事件注解，这样就不用setOnClickListener了
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.iv_activity_show_master_back:
                finish();
                break;
        }
    }
    private void initLocation()
    {
        locationClient=new LocationClient(this,getLocOption());
        locationClient.registerLocationListener(this);
        locationClient.start();
    }
    private LocationClientOption getLocOption() {
        LocationClientOption option=new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
        option.setCoorType("bd0911");
        option.setScanSpan(3 * 1000);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        return option;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();           //将地图的生命周期和activity绑定
        masterManager.requestQueue.cancelAll(MasterManager.class);
    }
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();            //将地图的生命周期和activity绑定
    }
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();             //将地图的生命周期和activity绑定
    }

    @Override
    public void onReceiveLocation(final BDLocation bdLocation) {
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude()))
                .zoom(16)
                .build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        mBaiduMap.animateMapStatus(mMapStatusUpdate);           //当定位返回数据后将地图中心移动到用户当前位置
        HashMap<String,String> map=new HashMap<>();
        map.put("lon",bdLocation.getLongitude()+"");
        map.put("lat", bdLocation.getLatitude() + "");
        map.put("radius", 1 + "");
        masterManager.getAroundMaster(map, new ICallBack() {
            @Override
            public void onSuccess(String string) {
                AroundMasterEntity entity = JSONObject.parseObject(string, AroundMasterEntity.class);
                if (entity.getRc() == 0) {
                    aroundMasters.addAll(entity.getRepairers());
                    for (int i = 0; i < aroundMasters.size(); i++) {                //添加覆盖物
                        Marker marker = null;
                        LatLng latLng1 = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                        BitmapDescriptor bitmap;
                        bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.repairer);
                        OverlayOptions options = new MarkerOptions().position(latLng1).icon(bitmap);
                        marker = (Marker) (mBaiduMap.addOverlay(options));
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("info", aroundMasters.get(i));
                        marker.setExtraInfo(bundle);
                    }
                    mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            final AroundMasterEntity.RepairersEntity info = (AroundMasterEntity.RepairersEntity) marker.getExtraInfo().get("info");
                            popView = LayoutInflater.from(ShowMasterActivity.this).inflate(R.layout.pop_layout, null);
                            TextView name = ((TextView) popView.findViewById(R.id.tv_pop_layout_name));
                            ImageView ivAvatar = (ImageView) popView.findViewById(R.id.iv_pop_layout_avatar);
                            ivAvatar.setOnClickListener(new View.OnClickListener() {            //当点击师傅头像的时候，跳转到师傅详情界面
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(ShowMasterActivity.this, RepairerDetailActivity.class);
                                    intent.putExtra("repairerId",info.getId());
                                    startActivity(intent);
                                }
                            });
                            TextView skill = ((TextView) popView.findViewById(R.id.tv_pop_layout_skill));
                            TextView phone = ((TextView) popView.findViewById(R.id.tv_pop_layout_phone));
                            ImageView star1 = (ImageView) popView.findViewById(R.id.iv_pop_layout_star1);
                            ImageView star2 = ((ImageView) popView.findViewById(R.id.iv_pop_layout_star2));
                            ImageView star3 = ((ImageView) popView.findViewById(R.id.iv_pop_layout_star3));
                            ImageView star4 = ((ImageView) popView.findViewById(R.id.iv_pop_layout_star4));
                            ImageView star5 = ((ImageView) popView.findViewById(R.id.iv_pop_layout_star5));
                            name.setText(info.getName());
                            skill.setText(info.getField());
                            InfoWindow infoWindow = new InfoWindow(popView, new LatLng(marker.getPosition().latitude, marker.getPosition().longitude), -1);

                            mBaiduMap.showInfoWindow(infoWindow);           //显示信息窗
                            return false;
                        }

                    });
                    mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
                        @Override
                        public void onMapClick(LatLng latLng) {
                            mBaiduMap.hideInfoWindow();         //当点击地图的时候隐藏信息窗
                        }

                        @Override
                        public boolean onMapPoiClick(MapPoi mapPoi) {
                            return false;
                        }
                    });
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        });

    }
}
